package qiniufile

import (
	"context"
	"path"

	"mall/common/globalkey"
	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DownloadFileLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDownloadFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DownloadFileLogic {
	return &DownloadFileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DownloadFileLogic) DownloadFile(req *types.UUIDPathReq) (filePath string, err error) {
	file, err := l.svcCtx.AttachmentRpc.BackendGetFileById(l.ctx, &attachmentclient.FileIdReq{
		Id: req.Id,
	})
	if err != nil {
		return "", err
	}

	if file.Status != nil && *file.Status == uint32(globalkey.AttachmentStatusPublish) {
		logx.Infow(
			"public download",
			logx.Field("fileName", *file.Filename),
			logx.Field("userId", l.ctx.Value("userId").(string)),
			logx.Field("filePath", *file.Path),
		)

		return path.Join(l.svcCtx.Config.NfsConf.PathPrefix, *file.Path), nil
	}

	logx.Infow(
		"private download",
		logx.Field("fileName", *file.Filename),
		logx.Field("userId", l.ctx.Value("userId").(string)),
		logx.Field("filePath", *file.Path),
	)

	return path.Join(l.svcCtx.Config.NfsConf.PathPrefix, *file.Path), nil
}
